package com.chensheng.aspect;

import com.chensheng.constant.CookieConstant;
import com.chensheng.constant.RedisConstant;
import com.chensheng.exception.SellerAuthorizedException;
import com.chensheng.redis.RedisService;
import com.chensheng.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class SellerAuthorizedAspect {

    @Autowired
    private RedisService redisService;

    @Pointcut("execution(public * com.chensheng.controller.Seller*.*(..))" +
            "&& !execution(public * com.chensheng.controller.SellerUserController.*(..))")
    public void verify(){}


    @Before("verify()")
    public void doVerify(){
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        //查询Cookie
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if(cookie == null){
            log.error("【登录校验】cookie查不到token");
            throw new SellerAuthorizedException();
        }

        String sellerId = redisService.get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if(StringUtils.isEmpty(sellerId)){
            log.error("【登录校验】redis中查询不到相应token");
            throw new SellerAuthorizedException();
        }
    }
}
